package com.just.fun.thread;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadSyncABC2 {
    private static ReentrantLock lock=new ReentrantLock();
    private static Condition c1=lock.newCondition();
    private static Condition c2=lock.newCondition();
    private static Condition c3=lock.newCondition();
    private static CountDownLatch countB=new CountDownLatch(1);
    private static CountDownLatch countC=new CountDownLatch(1);

    public static void main(String[] args) {
        int totalCount=10;
        //打印A
        Thread t1=new Thread(()->{
            try{
                lock.lock();
                for (int i = 0; i < totalCount; i++) {
                    System.out.print("A");
                    c2.signal();
                    //唤醒之后打开门闩
                    if(i==0){
                        countB.countDown();
                    }
                    c1.await();
                }
                c2.signal();
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }

        });

        //打印B
        Thread t2=new Thread(()->{
            try {
                countB.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            try{
                lock.lock();
                for (int i = 0; i < totalCount; i++) {
                    System.out.print("B");
                    c3.signal();
                    if(i==0){
                        countC.countDown();
                    }
                    c2.await();
                }
                c3.signal();
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        });

        //打印C
        Thread t3=new Thread(()->{
            try {
                countC.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            try{
                lock.lock();
                for (int i = 0; i < totalCount; i++) {
                    System.out.print("C\n");
                    c1.signal();
                    c3.await();
                }
                c1.signal();
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        });


        t2.start();

        t1.start();

        t3.start();

    }
}
